package com.mybatispuls.springboot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mybatispuls.springboot.Utils.JwtUtils;
import com.mybatispuls.springboot.entity.UcenterMember;
import com.mybatispuls.springboot.entity.Vo.UcenterVo;
import com.mybatispuls.springboot.mapper.UcenterMemberMapper;
import com.mybatispuls.springboot.service.UcenterMemberService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * <p>
 * 会员表 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2020-05-22
 */
@Service
public class UcenterMemberServiceImpl extends ServiceImpl<UcenterMemberMapper, UcenterMember> implements UcenterMemberService {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Override
    public String login(UcenterMember ucenterMember) {
        //手机号码
        String mobile = ucenterMember.getMobile();
        //密码
        String password = ucenterMember.getPassword();

        QueryWrapper<UcenterMember> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mobile",mobile);
        UcenterMember member = baseMapper.selectOne(queryWrapper);
        String nickname = member.getNickname();

        if (!StringUtils.isEmpty(member)){
            String passMd5 = new Md5Hash(password,nickname).toString();
            if (passMd5.equals(member.getPassword())){
                //登录成功
                //生成token字符串，使用jwt工具类
                String jwtToken = JwtUtils.getJwtToken(member.getId(), member.getNickname());
                return jwtToken;
            }

        }

        return null;
    }

    //注册
    @Override
    public void insert(UcenterVo ucenterVo) {
        //输入的验证码
        String code = ucenterVo.getCode();
        String mobile = ucenterVo.getMobile();
        String nickname = ucenterVo.getNickname();
        String password = ucenterVo.getPassword();
        //加密后的密码
        String passMd5 = new Md5Hash(password,nickname).toString();
        UcenterMember member = new UcenterMember();
        member.setMobile(mobile);
        member.setNickname(nickname);
        member.setPassword(passMd5);
        //从redis中获取的验证码
        String Verification = redisTemplate.opsForValue().get(mobile);
        if (code.equals(Verification)){
            baseMapper.insert(member);
        }

    }



}
